//!
//! Copyright (c) 2024-2999 北京心月狐科技有限公司 All rights reserved.
//!
//! https://www.mxxshop.com
//!
//! Licensed 并不是自由软件，未经许可不能去掉 MxxShop 相关版权
//!
//! 版权所有，侵权必究！
//!

use regex::Regex;
use std::borrow::Cow;
use actix_session::Session;
use crate::core::errors::error::{Error, Result};
use crate::core::web::entity::common::QueryUrl;
use actix_web::{HttpResponse, web, get};
use actix_web::http::header::ContentType;
use actix_web::web::Redirect;
use minijinja::context;
use crate::core::service::template_service::get_template;
use crate::modules::articles::entity::article_model::{Info, ArticleVO};
use crate::modules::articles::service::article_service;

pub async fn article_list(session: Session,info: web::Path<Info>) -> Result<HttpResponse> {
    
    
    let ctx = context!(
        title => "MxxShop",
    );
    let out = get_template("default/article/list_article.html", ctx)?;
    Ok(HttpResponse::Ok().content_type(ContentType::html()).body(out))
}


///文章详细页面
#[get("/news/{short_url}")]
pub async fn article_detail(session: Session, path: web::Path<QueryUrl>) -> Result<HttpResponse> {
    let s_short_url = path.short_url.clone();
    if s_short_url.is_some() {
        Redirect::to("/error/400").permanent();
    }
    
    let data = article_service::get_by_short_url(s_short_url).await?.ok_or_else(|| { Error::from(format!("msg={},code={}", "未获取到公司信息".to_string(), 404))})?;
    
    let mut article_data = ArticleVO::from(data);

    let re = Regex::new(r#"<[^>]*>"#).unwrap();
    let stripped_content = if let Some(content) = &article_data.content {
        re.replace_all(content, "")
    } else {
        Cow::Borrowed("")
    };

    article_data.description = Some(stripped_content.to_string());


    let ctx = context!(
        title => "MxxShop",
        article => article_data,
    );
    let out = get_template("default/article/detail.html", ctx)?;
    Ok(HttpResponse::Ok().content_type(ContentType::html()).body(out))
}

